from django.shortcuts import render, redirect
from rbac.service.init_permission import init_permission
from web.utils.md5 import gen_md5
from web import models


def login(request):
    """
    登录
    :param request:
    :return:
    """
    if request.method == 'GET':
        return render(request, 'web/login.html')

    user = request.POST.get('user')
    pwd = gen_md5(request.POST.get('pwd', ''))
    current_user = models.UserInfo.objects.filter(username=user, password=pwd).first()
    if not current_user:
        msg = '用户名和密码错误，请重新输入'
        return render(request, 'web/login.html', {'msg': msg})

    request.session['user_info'] = {'user_id': current_user.id, 'nickname': current_user.nickname}

    # 权限信息初始化
    init_permission(request, current_user)
    if pwd == gen_md5('123456'):
        return redirect('/current/userinfo/')
    return redirect('/index/')


def logout(request):
    """
    推出
    :param request:
    :return:
    """
    request.session.delete()
    return redirect('/login/')


def index(request):
    return render(request, 'web/index.html')


def login1(request):
    return render(request, 'web/login.html')